package net.lwf.web.tags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import net.lwf.util.web.WebUtil;
import net.lwf.web.constant.IWebConstant;

import lwf.handler.entities.RadioData;

public class RadioAnswerChoiceTag extends TagSupport {

	private static final long serialVersionUID = 1L;
	private String onClick    = "";
	private String style       = "";
	private String rowsonly = "false";

	public int doEndTag() throws JspException {

		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		try {
			pageContext.getOut().println(this.generateRadioChoices(request));
		} catch (IOException e) {
			throw new JspException(e.getMessage());
		}
			return EVAL_PAGE;
	}


	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}

	public String getOnClick() {
		return onClick;
	}


	public void setOnClick(String onClick) {
		this.onClick = onClick;
	}

	public String getRowsonly() {
		return rowsonly;
	}

	public void setRowsonly(String rowsonly) {
		this.rowsonly = rowsonly;
	}


	private String generateRadioChoices(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		Object dataobj = WebUtil.getAttribute(request, IWebConstant.RADIO_ANSWERS);
		if(dataobj != null) {
			@SuppressWarnings("unchecked")
			List<RadioData> data = (ArrayList <RadioData>) dataobj;
			if(data != null) {
				sb.append("<table>");
				if(this.rowsonly.equalsIgnoreCase("true")) {
					
					for(RadioData rdata: data) {
						sb.append("<tr>");
							sb.append("<td>");
								sb.append("<input type=\"radio\" name=\"choices\" value=\"" + rdata.getAnswer() + "\" onClick=\"" + this.onClick + "\" >" );
							sb.append("</td>");
							sb.append("<td>");
								sb.append(rdata.getDisplay());
							sb.append("</td>");
							sb.append("<td>&nbsp;</td>");
						sb.append("</tr>");
					}
					
				}
				else {
					sb.append("<tr>");
					for(RadioData rdata: data) {
						sb.append("<td>");
							sb.append("<input type=\"radio\" name=\"choices\" value=\"" + rdata.getAnswer() + "\" onClick=\"" + this.onClick + "\" >" );
						sb.append("</td>");
						sb.append("<td>");
							sb.append(rdata.getDisplay());
						sb.append("</td>");
						sb.append("<td>&nbsp;</td>");
					}
					sb.append("</tr>");					
				}

				sb.append("</table>");
			}
		}


		return sb.toString();
	}

}
